import { join, dirname, basename } from 'path';
import { existsSync, readFileSync, writeFileSync } from 'fs';

export default function(api) {
  const { utils,paths } = api;
  const { Mustache } = utils;
  api.describe({
    key: 'cas',
    config: {
      onChange: api.ConfigChangeType.regenerateTmpFiles,
      schema(joi) {
        return joi.object();
      },
    },
    enableBy: api.EnableBy.config,
  });
  api.addRuntimePluginKey(() => 'cas');
  api.addRuntimePlugin(() => join(paths.absTmpPath, 'plugin-cas/runtime.js'));

  api.onGenerateFiles(() => {
    const opts = api.userConfig.cas;
    const { exclude } = opts;
    let isExclude = false;
    if (exclude) {
      isExclude = true;
    }

    const runTimeContent = readFileSync(join(__dirname, '../template/runtime.js.tpl'), 'utf-8');
    api.writeTmpFile({
      path: 'plugin-cas/runtime.js',
      content: Mustache.render(runTimeContent, {
        ...opts,
        isExclude,
      }),
    });

  });

  api.modifyConfig(memo => {
    return {
      ...memo,
      alias: {
        ...(memo.alias || {}),
        'ystec-cas': join(__dirname, './cas.js'),
      },
    };
  });
}
